package com.aitaoxue.palx.fragment;

import java.io.Serializable;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.aitaoxue.palx.R;
import com.aitaoxue.palx.adapter.ErrorBookAdapter;
import com.aitaoxue.palx.api.remote.AitaoXueApi;
import com.aitaoxue.palx.base.BaseListFragment;
import com.aitaoxue.palx.base.ListBaseAdapter;
import com.aitaoxue.palx.bean.ErrorBook;
import com.aitaoxue.palx.bean.ErrorBookCourse;
import com.aitaoxue.palx.bean.ErrorBookCourseList;
import com.aitaoxue.palx.bean.ErrorBookList;
import com.aitaoxue.palx.bean.ListEntity;
import com.aitaoxue.palx.ui.ErrorBookItemActivity;
import com.aitaoxue.palx.ui.empty.EmptyLayout;
import com.aitaoxue.palx.util.GsonUtil;
import com.aitaoxue.palx.widget.DateChooseDialog;
import com.aitaoxue.palx.widget.DateChooseDialog.OnDateSetListener;
import com.aitaoxue.palx.widget.RevealLayout;
import com.loopj.android.http.AsyncHttpResponseHandler;

public class ErrorBookFragment extends BaseListFragment {

	private String CACHE_KEY_PREFIX = "errorbook_";
	private static String order = "-1";

	private HashMap<String, String> params = null;
	// 时间筛选上限
	private String TIME_UP_KEY = "start";
	private String TIME_DOWN_KEY = "stop";
	private String TIME_UP;
	private String TIME_DOWN;

	// 科目筛选
	private String COURSE_FILTER = "errorBookId";

	// -1为降序,1为升序
	private static int currentOrder = -1;

	private List<ErrorBookCourse> courseList;

	private void setCacheKey(String key) {
		CACHE_KEY_PREFIX = key;
	}

	// 时间排序
	protected RevealLayout first;
	// 时间图标
	protected ImageView timeIco;
	// 时间筛选
	protected RevealLayout second;
	private TextView timeFilter;
	// 科目
	protected RevealLayout third;
	private TextView courseTitle;

	@Override
	protected String getCacheKeyPrefix() {
		return CACHE_KEY_PREFIX;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		setCacheKey("errorbook_"
				+ activity.getIntent().getStringExtra("userid"));
	}

	@Override
	public void initView(View view) {
		first = (RevealLayout) view.findViewById(R.id.layout_first);
		second = (RevealLayout) view.findViewById(R.id.layout_second);
		third = (RevealLayout) view.findViewById(R.id.layout_third);
		timeIco = (ImageView) view.findViewById(R.id.time_ico);
		timeFilter = (TextView) view.findViewById(R.id.filter_time);
		courseTitle = (TextView) view.findViewById(R.id.course);

		super.initView(view);

		first.setOnClickListener(this);
		second.setOnClickListener(this);
		third.setOnClickListener(this);

		params = new HashMap<String, String>();

		// 获得错题本科目列表
		AitaoXueApi.getUserErrorBook(
				getActivity().getIntent().getStringExtra("userid"), handler);
	}

	@Override
	protected ListBaseAdapter getListAdapter() {
		return new ErrorBookAdapter(getActivity());
	}

	@Override
	protected int getLayoutId() {
		return R.layout.fragment_error_book;
	}

	@Override
	protected void sendRequestData(Map<String, String> map) {
		AitaoXueApi.selectErrorBookByDays(map, getActivity().getIntent()
				.getStringExtra("userid"), String.valueOf(mCurrentPage), order,
				mhandler);

	}

	@Override
	protected ListEntity parseList(byte[] response) throws Exception {
		String res = new String(response);

		ErrorBookList list = GsonUtil.GsonToBean(res, ErrorBookList.class);

		return list;
	}

	@Override
	protected ListEntity readList(Serializable seri) {
		return (ErrorBookList) seri;
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.layout_first:
			if (currentOrder == -1) {
				currentOrder = 1;
				timeIco.setImageResource(R.drawable.time_up);
				order = "1";
			} else {
				currentOrder = -1;
				timeIco.setImageResource(R.drawable.time_down);
				order = "-1";
			}
			setCacheKey(null);
			refreshData(params);
			break;
		case R.id.layout_second:
			// 产生时间选择器
			final Calendar c = Calendar.getInstance();
			DateChooseDialog dialog = new DateChooseDialog(getActivity(), 0,
					c.get(Calendar.YEAR), c.get(Calendar.MONTH),
					c.get(Calendar.DATE), "start", new OnDateSetListener() {

						@Override
						public void onDateSet(DatePicker picker, int year,
								int month, int day) {
							if (picker == null) {
								TIME_UP = "不限";
								if (params.containsKey(TIME_UP_KEY)) {
									params.remove(TIME_UP_KEY);
								}
							} else {
								TIME_UP = year + "-" + month + "-" + day;
								params.put(TIME_UP_KEY, TIME_UP);
							}

							// 产生下一个时间选择框
							DateChooseDialog dialog2 = new DateChooseDialog(
									getActivity(), 0, c.get(Calendar.YEAR),
									c.get(Calendar.MONTH),
									c.get(Calendar.DATE), "stop",
									new OnDateSetListener() {

										@Override
										public void onDateSet(
												DatePicker picker, int year,
												int month, int day) {
											if (picker == null) {
												TIME_DOWN = "不限";
												if (params
														.containsKey(TIME_DOWN_KEY)) {
													params.remove(TIME_DOWN_KEY);
												}
											} else {
												TIME_DOWN = year + "-" + month
														+ "-" + day;
												params.put(TIME_DOWN_KEY,
														TIME_DOWN);
											}

											timeFilter.setText(TIME_UP + "/"
													+ TIME_DOWN);

											setCacheKey(null);
											refreshData(params);

										}
									});
							dialog2.show();
						}
					});
			dialog.show();
			break;
		case R.id.layout_third:
			// 弹出popwindow
			final PopupWindow window = new PopupWindow(getActivity());
			LayoutInflater inflater = LayoutInflater.from(getActivity()
					.getApplicationContext());
			View popupView = inflater.inflate(R.layout.popup_window_listview,
					null);
			window.setWidth(200);
			window.setHeight(LayoutParams.WRAP_CONTENT);
			window.setContentView(popupView);
			window.setFocusable(true);
			window.setOutsideTouchable(true);

			ListView listview = (ListView) popupView
					.findViewById(R.id.popupwindow);
			CourseAdapter adapter = new CourseAdapter(getActivity(), courseList);
			listview.setAdapter(adapter);

			listview.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					if (position == 0) {
						courseTitle.setText("科目");
						if (params.containsKey(COURSE_FILTER)) {
							params.remove(COURSE_FILTER);
						}
					} else {
						courseTitle.setText(courseList.get(position - 1)
								.getBook_name());
						params.put(COURSE_FILTER, courseList.get(position - 1)
								.getError_book_id());
					}

					window.dismiss();

					setCacheKey(null);
					refreshData(params);
				}
			});

			window.showAsDropDown(third);
			break;
		default:
			break;
		}
	}

	private void refreshData(Map<String, String> map) {
		mListView.setSelection(0);
		mCurrentPage = 1;
		mState = STATE_REFRESH;
		mErrorLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
		requestData(true, map);
	}

	private AsyncHttpResponseHandler handler = new AsyncHttpResponseHandler() {

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
			String res = new String(arg2);

			ErrorBookCourseList list = GsonUtil.GsonToBean(res,
					ErrorBookCourseList.class);

			courseList = list.getList();
		}

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
				Throwable arg3) {
		}
	};

	private class CourseAdapter extends BaseAdapter {

		private Context context;
		private List<ErrorBookCourse> list;

		public CourseAdapter(Context context, List<ErrorBookCourse> list) {
			this.context = context;
			this.list = list;
		}

		@Override
		public int getCount() {
			return list.size() + 1;
		}

		@Override
		public Object getItem(int position) {
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			convertView = LayoutInflater.from(context).inflate(
					R.layout.popup_window_cell, null);
			TextView cell = (TextView) convertView.findViewById(R.id.cell);

			if (position == 0) {
				cell.setText("所有");
			} else {
				ErrorBookCourse course = list.get(position - 1);
				cell.setText(course.getBook_name() + "("
						+ course.getPage_count() + ")");
			}

			return convertView;
		}

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// 进入错题详情页面
		ErrorBook errorBook = (ErrorBook) mAdapter.getItem(position);

		Intent intent = new Intent(getActivity(), ErrorBookItemActivity.class);
		intent.putExtra("desc", errorBook.getPage_desc());
		intent.putExtra("img_url", errorBook.getPage_picture());
		startActivity(intent);
	}

}
